package com.atguigu.controller;

import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;


@RestController
@RequestMapping("ai")
public class LangChain4jController {

    @Autowired
    @Qualifier(value = "ollamaChatModel")//阻塞式
    ChatLanguageModel chatLanguageModel;

    @Qualifier(value = "ollamaStreamingChatModel")//流式式
    @Autowired
    StreamingChatLanguageModel streamingChatLanguageModel;

    @GetMapping("chat")
    public String chat(String msg){
        return chatLanguageModel.chat(msg);
    }

    @RequestMapping("stream")
    public Flux<String> stream(@RequestBody String msg){
        //使用Flux的方法处理流式调用的结构
        return Flux.create(e-> {
            streamingChatLanguageModel.chat(msg,
                    new StreamingChatResponseHandler() {
                        @Override
                        public void onPartialResponse(String s) {
                            //使用e 处理正在进行中的流式数据
                            e.next(s);
                        }

                        @Override
                        public void onCompleteResponse(ChatResponse chatResponse) {
                            //使用e 处理完成的流式调用
                            e.complete();
                        }

                        @Override
                        public void onError(Throwable throwable) {
                            //处理异常
                            e.error(throwable);
                        }
                    });
        });



    }
}
